﻿using MSharp.Data.DatabaseInfo;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MSharp.Data.Database
{
    public class PostgreSqlDB : DB
    {
        public PostgreSqlDB(DBType dbType, DbProviderFactory dbFactory, string connectionString) 
            : base(dbType, dbFactory, connectionString)
        {
            this.Info = new PostgreSqlDBInfo(this);
        }

        internal override Ret InsertGet<DT, Ret>(DT data, string tableName, params string[] excludeColNames)
        {
            var kv = InsertScript(data, tableName, excludeColNames);
            using (var conn = CreateConn())
            {
                var cmd = conn.CreateCommand();

                try
                {
                    PostgreSqlDBInfo postgreInfo = Info as PostgreSqlDBInfo;

                    cmd.CommandText = kv.Key + ";" + SqlScript.IdentitySql(DBType, tableName, null, postgreInfo.IdentityColumnName(tableName));

                    PrepareCommand(cmd, conn, null, cmd.CommandText, kv.Value, 30);

                    var result2 = cmd.ExecuteScalar().ChangeType<Ret>();

                    if (OnExecuted != null)
                    {
                        OnExecuted.Invoke(cmd.CommandText, null, result2);
                    }

                    return result2;
                }
                catch (Exception ex)
                {
                    if (this.OnError != null)
                        this.OnError.Invoke(cmd.CommandText, cmd.Parameters, ex);
                    throw ex;
                }
            }
        }

        public override int InsertGetInt<DT>(DT data, string tableName, params string[] excludeColNames)
        {
            return InsertGet<DT, int>(data, tableName, excludeColNames);
        }

        public override long InsertGetLong<DT>(DT data, string tableName, params string[] excludeColNames)
        {
            return InsertGet<DT, long>(data, tableName, excludeColNames);
        }
    }
}
